import { useState, useEffect, useCallback, useMemo } from 'react'
import Taro from '@tarojs/taro'
import { get } from '../axios/aiaxios/request'

// 环境检测
const isDev = process.env.NODE_ENV === 'development'
const log = isDev ? console.log : () => {}

// 轮播图数据
export const useBannersData = () => {
  const [bannersData, setBannersData] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchBanners = async () => {
      try {
        setLoading(true)
        const response = await get('/cosmetic/banners')
        
        log('轮播图API响应:', response)
        
        if (response.success) {
          const data = response.data || []
          log('轮播图原始数据:', data)
          setBannersData(Array.isArray(data) ? data : [])
          log('轮播图数据加载成功:', Array.isArray(data) ? data.length : 0, '条')
        } else {
          log('轮播图数据加载失败:', response)
          // 使用备用数据
          const fallbackBanners = [
            {
              id: 'banner001',
              image: 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=800&h=400&fit=crop',
              title: '享SHOW盛夏',
              subtitle: '超级补贴',
              tag: 'HOT',
              offer: '瘦肩瘦腿200U ¥999起'
            },
            {
              id: 'banner002',
              image: 'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=800&h=400&fit=crop',
              title: '美丽蜕变',
              subtitle: '限时特惠',
              tag: 'SALE',
              offer: '玻尿酸填充 ¥1280起'
            }
          ]
          setBannersData(fallbackBanners)
        }
      } catch (error) {
        log('轮播图数据加载错误:', error)
        // 使用备用数据
        const fallbackBanners = [
          {
            id: 'banner001',
            image: 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=800&h=400&fit=crop',
            title: '享SHOW盛夏',
            subtitle: '超级补贴',
            tag: 'HOT',
            offer: '瘦肩瘦腿200U ¥999起'
          },
          {
            id: 'banner002',
            image: 'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=800&h=400&fit=crop',
            title: '美丽蜕变',
            subtitle: '限时特惠',
            tag: 'SALE',
            offer: '玻尿酸填充 ¥1280起'
          }
        ]
        setBannersData(fallbackBanners)
      } finally {
        setLoading(false)
      }
    }

    fetchBanners()
  }, [])

  return bannersData
}

// 商品数据
export const useProductsData = () => {
  const [allProducts, setAllProducts] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchProducts = async () => {
      try {
        setLoading(true)
        const response = await get('/cosmetic/products', { limit: 100 })
        
        console.log('商品API响应:', response)
        
        if (response.success) {
          const rawData = response.data || []
          setAllProducts(rawData)
          console.log('商品数据加载成功:', rawData.length, '个商品')
        } else {
          console.error('商品数据加载失败:', response)
          setAllProducts([])
        }
      } catch (error) {
        console.error('商品数据加载错误:', error)
        setAllProducts([])
      } finally {
        setLoading(false)
      }
    }

    fetchProducts()
  }, [])

  // 根据标签筛选商品
  const getProductsByTag = useCallback((tag) => {
    if (!allProducts || allProducts.length === 0) return []
    
    // 推荐标签显示所有商品
    if (tag === '推荐') {
      return allProducts
    }
    
    // 根据商品的tags数组筛选
    return allProducts.filter(product => {
      if (!product.tags || !Array.isArray(product.tags)) return false
      return product.tags.includes(tag)
    })
  }, [allProducts])

  // 获取所有可用的标签
  const getAllTags = useCallback(() => {
    if (!allProducts || allProducts.length === 0) return ['推荐']
    
    const tagSet = new Set(['推荐']) // 默认添加推荐标签
    
    allProducts.forEach(product => {
      if (product.tags && Array.isArray(product.tags)) {
        product.tags.forEach(tag => {
          if (tag && tag.trim()) {
            tagSet.add(tag.trim())
          }
        })
      }
    })
    
    return Array.from(tagSet)
  }, [allProducts])

  return { 
    allProducts, 
    getProductsByTag, 
    getAllTags,
    loading 
  }
}

// 医院数据
export const useHospitalsData = () => {
  const [hospitalsData, setHospitalsData] = useState({
    '推荐': [] // 初始化推荐分类，避免undefined
  })
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchHospitals = async () => {
      try {
        setLoading(true)
        const response = await get('/cosmetic/hospitals', { limit: 100 })
        
        console.log('医院API响应:', response)
        console.log('医院API响应类型:', typeof response)
        console.log('医院API响应success:', response.success)
        console.log('医院API响应data:', response.data)
        
        if (response.success) {
          const rawData = response.data || []
          console.log('医院原始数据:', rawData)
          console.log('医院原始数据长度:', rawData.length)
          
          // 检查第一个医院的商品数据
          if (rawData.length > 0) {
            console.log('第一个医院的商品数据:', rawData[0].products)
            console.log('第一个医院商品数量:', rawData[0].products?.length || 0)
          }
          
          // 将数组按分类组织成对象
          const organizedData = {}
          
          // 添加"推荐"分类，包含所有医院
          organizedData['推荐'] = rawData
          console.log('推荐分类数据:', organizedData['推荐'])
          
          // 按实际分类组织数据
          rawData.forEach(hospital => {
            const category = hospital.category || '热门'
            if (!organizedData[category]) {
              organizedData[category] = []
            }
            organizedData[category].push(hospital)
          })
          
          setHospitalsData(organizedData)
          console.log('医院数据加载成功:', Object.keys(organizedData).length, '个分类')
          console.log('推荐分类医院数量:', organizedData['推荐']?.length || 0)
          console.log('医院数据详情:', organizedData)
        } else {
          console.error('医院数据加载失败:', response)
          // 使用备用数据
          const fallbackData = [
            {
              id: 'hosp001',
              name: '美莱医疗美容医院',
              logo: 'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?w=100&h=100&fit=crop',
              rating: 4.8,
              services: 1200,
              reviews: 500,
              tag: '北京市医美医院人气热销榜第1名',
              category: '民营',
              products: [
                {
                  id: 'prod001',
                  title: '玻尿酸填充',
                  price: 1280,
                  saved: 700,
                  image: 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=300&h=200&fit=crop'
                }
              ]
            }
          ]
          
          setHospitalsData({
            '推荐': fallbackData,
            '民营': fallbackData,
            '热门': fallbackData
          })
        }
      } catch (error) {
        console.error('医院数据加载错误:', error)
        // 使用备用数据
        const fallbackData = [
          {
            id: 'hosp001',
            name: '美莱医疗美容医院',
            logo: 'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?w=100&h=100&fit=crop',
            rating: 4.8,
            services: 1200,
            reviews: 500,
            tag: '北京市医美医院人气热销榜第1名',
            category: '民营',
            products: [
              {
                id: 'prod001',
                title: '玻尿酸填充',
                price: 1280,
                saved: 700,
                image: 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=300&h=200&fit=crop'
              }
            ]
          }
        ]
        
        setHospitalsData({
          '推荐': fallbackData,
          '民营': fallbackData,
          '热门': fallbackData
        })
      } finally {
        setLoading(false)
      }
    }

    fetchHospitals()
  }, [])

  return { hospitalsData, loading }
}

// 医生数据
export const useDoctorsData = () => {
  const [allDoctors, setAllDoctors] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchDoctors = async () => {
      try {
        setLoading(true)
        const response = await get('/cosmetic/doctors', { limit: 100 })
        
        console.log('医生API响应:', response)
        
        if (response.success) {
          const rawData = response.data || []
          setAllDoctors(rawData)
          console.log('医生数据加载成功:', rawData.length, '个医生')
          console.log('医生数据详情:', rawData)
        } else {
          console.error('医生数据加载失败:', response)
          // 使用备用数据
          const fallbackDoctors = [
            {
              id: 'doc001',
              name: '张医生',
              hospital: '美莱医疗美容医院',
              avatar: 'https://images.unsplash.com/photo-1559839734-2b71ea197ec2?w=100&h=100&fit=crop&crop=face',
              specialties: ['眼部整形', '面部轮廓'],
              tag: '主任医师',
              category: '热门',
              products: [
                {
                  id: 'product001',
                  title: '玻尿酸填充',
                  price: 1280,
                  saved: 700,
                  image: 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=300&h=200&fit=crop'
                }
              ]
            },
            {
              id: 'doc002',
              name: '李医生',
              hospital: '华美医疗美容医院',
              avatar: 'https://images.unsplash.com/photo-1612349317150-e413f6a5b16d?w=100&h=100&fit=crop&crop=face',
              specialties: ['眼部整形', '美体塑形'],
              tag: '副主任医师',
              category: '眼部整形',
              products: [
                {
                  id: 'product002',
                  title: '瘦脸针',
                  price: 680,
                  saved: 300,
                  image: 'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=300&h=200&fit=crop'
                }
              ]
            }
          ]
          setAllDoctors(fallbackDoctors)
        }
      } catch (error) {
        console.error('医生数据加载错误:', error)
        // 使用备用数据
        const fallbackDoctors = [
          {
            id: 'doc001',
            name: '张医生',
            hospital: '美莱医疗美容医院',
            avatar: 'https://images.unsplash.com/photo-1559839734-2b71ea197ec2?w=100&h=100&fit=crop&crop=face',
            specialties: ['眼部整形', '面部轮廓'],
            tag: '主任医师',
            category: '热门',
            products: [
              {
                id: 'product001',
                title: '玻尿酸填充',
                price: 1280,
                saved: 700,
                image: 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=300&h=200&fit=crop'
              }
            ]
          },
          {
            id: 'doc002',
            name: '李医生',
            hospital: '华美医疗美容医院',
            avatar: 'https://images.unsplash.com/photo-1612349317150-e413f6a5b16d?w=100&h=100&fit=crop&crop=face',
            specialties: ['眼部整形', '美体塑形'],
            tag: '副主任医师',
            category: '眼部整形',
            products: [
              {
                id: 'product002',
                title: '瘦脸针',
                price: 680,
                saved: 300,
                image: 'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=300&h=200&fit=crop'
              }
            ]
          }
        ]
        setAllDoctors(fallbackDoctors)
      } finally {
        setLoading(false)
      }
    }

    fetchDoctors()
  }, [])

  // 根据分类筛选医生
  const getDoctorsByCategory = useCallback((category) => {
    if (category === '推荐') {
      return allDoctors
    }
    return allDoctors.filter(doctor => doctor.category === category)
  }, [allDoctors])

  // 获取所有分类标签
  const getAllCategories = useCallback(() => {
    const categories = ['推荐']
    const existingCategories = [...new Set(allDoctors.map(doctor => doctor.category).filter(Boolean))]
    // 确保"推荐"在最前面，排除"热门"避免混淆
    const filteredCategories = existingCategories.filter(cat => cat !== '推荐' && cat !== '热门')
    return [...categories, ...filteredCategories]
  }, [allDoctors])

  return { 
    allDoctors, 
    getDoctorsByCategory, 
    getAllCategories, 
    loading 
  }
}

// 商品筛选标签 - 现在从商品数据中动态获取
export const useProductFilterTags = (getAllTags) => {
  const [filterTags, setFilterTags] = useState(['推荐'])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (getAllTags) {
      const tags = getAllTags()
      setFilterTags(tags)
      setLoading(false)
      console.log('商品标签加载成功:', tags.length, '个标签:', tags)
    }
  }, [getAllTags])

  return { filterTags, loading }
}

// 医院筛选标签
export const useHospitalFilterTags = () => {
  const [filterTags, setFilterTags] = useState(['推荐'])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchFilterTags = async () => {
      try {
        setLoading(true)
        const response = await get('/cosmetic/hospitals/categories')
        
        console.log('医院分类API响应:', response)
        
        if (response.success) {
          const data = response.data || []
          // 将"推荐"放在最前面，然后添加其他分类
          const tags = ['推荐', ...data.filter(tag => tag !== '推荐')]
          setFilterTags(tags)
          console.log('医院分类标签加载成功:', tags.length, '个')
        } else {
          console.error('医院分类标签加载失败:', response)
          setFilterTags(['推荐', '民营', '公立'])
        }
      } catch (error) {
        console.error('医院分类标签加载错误:', error)
        setFilterTags(['推荐', '民营', '公立'])
      } finally {
        setLoading(false)
      }
    }

    fetchFilterTags()
  }, [])

  return { filterTags, loading }
}

// 医生筛选标签 - 现在从医生数据中动态获取
export const useDoctorFilterTags = (getAllCategories) => {
  const [filterTags, setFilterTags] = useState(['推荐'])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (getAllCategories) {
      const categories = getAllCategories()
      setFilterTags(categories)
      setLoading(false)
      console.log('医生标签加载成功:', categories.length, '个标签:', categories)
    }
  }, [getAllCategories])

  return { filterTags, loading }
}

// 搜索功能
export const useSearch = () => {
  const [searchResults, setSearchResults] = useState({})
  const [searchSuggestions, setSearchSuggestions] = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

  const performSearch = async (keyword, type = 'all', page = 1, limit = 10, tab = 'all') => {
    if (!keyword || keyword.trim() === '') {
      setSearchResults({})
      return
    }

    try {
      setLoading(true)
      setError(null)
      
      const response = await get('/cosmetic/search', {
        keyword: keyword.trim(),
        type,
        tab, // 传递当前标签页
        page,
        limit
      })

      if (response.success) {
        const data = response.data || {}
        setSearchResults(data)
        console.log('搜索成功:', data)
        console.log('搜索结果详情:', {
          products: data.products?.length || 0,
          hospitals: data.hospitals?.length || 0,
          doctors: data.doctors?.length || 0,
          filteredResults: data.filteredResults?.length || 0
        })
      } else {
        throw new Error(response.message || '搜索失败')
      }
    } catch (error) {
      console.error('搜索错误:', error)
      setError(error.message)
      setSearchResults({})
    } finally {
      setLoading(false)
    }
  }

  const getSearchSuggestions = async (keyword, limit = 10) => {
    if (!keyword || keyword.trim() === '') {
      setSearchSuggestions([])
      return
    }

    try {
      const response = await get('/cosmetic/search/suggestions', {
        keyword: keyword.trim(),
        limit
      })

      if (response.success) {
        const suggestions = response.data || []
        setSearchSuggestions(suggestions)
      } else {
        setSearchSuggestions([])
      }
    } catch (error) {
      console.error('获取搜索建议错误:', error)
      setSearchSuggestions([])
    }
  }

  const clearSearch = () => {
    setSearchResults({})
    setSearchSuggestions([])
    setError(null)
  }

  return {
    searchResults,
    searchSuggestions,
    loading,
    error,
    performSearch,
    getSearchSuggestions,
    clearSearch
  }
}

// 热门搜索词
export const useHotSearch = () => {
  const [hotSearchWords, setHotSearchWords] = useState([])

  useEffect(() => {
    // 静态热门搜索词
    const hotWords = [
      '玻尿酸填充',
      '瘦脸针',
      '双眼皮',
      '隆鼻',
      '美白针',
      '水光针',
      '激光祛斑',
      '除皱针',
      '隆胸',
      '吸脂'
    ]
    setHotSearchWords(hotWords)
  }, [])

  return hotSearchWords
}
